package form

import (
	"context"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/repository/common/form"
	pb "git.mycaigou.com/gfyx/micro-gfyx-oppty-service/proto/micro_gfyx_oppty_service_proto/micro-gfyx-oppty-service/common"
)

type formService struct {
	formRepo form.FormRepoIface
}

func NewFormService(formRepo form.FormRepoIface) FormServiceIface {
	return &formService{
		formRepo: formRepo,
	}
}

// GetFormTemplateConfig 获取模板配置信息
func (f *formService) GetFormTemplateConfig(ctx context.Context, templateId string) (*pb.GetFormTemplateConfigResponse, error) {
	resp := pb.GetFormTemplateConfigResponse{Data: make([]*pb.GroupInfo, 0)}
	groupList, err := f.formRepo.GetFormGroupList(ctx, templateId)
	if err != nil {
		return &resp, err
	}
	if groupList == nil {
		return &resp, nil
	}
	condition := map[string]interface{}{}
	condition["is_deleted"] = 0
	condition["form_template_id"] = templateId
	filedList, err := f.formRepo.GetFormFieldList(ctx, condition)
	if err != nil {
		return &resp, err
	}
	if filedList == nil {
		return &resp, nil
	}
	for _, group := range groupList {
		groupInfo := &pb.GroupInfo{
			Uid:                 group.Uid,
			FieldName:           group.FieldName,
			FieldComponentProps: group.FieldComponentProps,
			Sort:                group.Sort,
		}
		for _, filed := range filedList {
			if filed.FormGroupUid == group.Uid {
				filedInfo := &pb.FiledInfo{
					Uid:                 filed.Uid,
					FieldName:           filed.FieldName,
					FormGroupUid:        filed.FormGroupUid,
					IsDefault:           filed.IsDefault,
					FieldComponent:      filed.FieldComponent,
					Required:            filed.Required,
					FieldComponentProps: filed.FieldComponentProps,
					Sort:                filed.Sort,
				}
				groupInfo.Children = append(groupInfo.Children, filedInfo)
			}
		}
		resp.Data = append(resp.Data, groupInfo)
	}

	return &resp, nil
}

// GetFormDataRuleList 获取数据规则
func (f *formService) GetFormDataRuleList(ctx context.Context, uids []string) (*pb.GetFormDataRuleResponse, error) {
	resp := pb.GetFormDataRuleResponse{
		Data: make([]*pb.DataRule, 0),
	}

	dataRuleList, err := f.formRepo.GetFormDataRuleList(ctx, uids)
	if err != nil {
		return nil, err
	}
	if dataRuleList != nil {
		for _, rule := range dataRuleList {
			resp.Data = append(resp.Data, &pb.DataRule{
				RuleKey:   rule.RuleKey,
				RuleValue: rule.RuleValue,
			})
		}
	}

	return &resp, nil
}
